package com.app.art.controller.common;

import cn.hutool.core.codec.Base64;
import com.app.art.service.redis.RedisService;
import com.atom.module.captcha.config.Captcha;
import com.atom.module.captcha.config.CaptchaEnum;
import com.atom.module.captcha.service.CaptchaService;
import com.atom.module.common.result.Result;
import com.atom.module.common.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.io.IOException;
import java.util.Map;

/**
 * 验证码操作处理
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    public static final String CAPTCHA_CODE_KEY = "captcha_codes:";

    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private RedisService redisService;

    /**
     * 生成验证码
     */
    @GetMapping("/image/{type}")
    public Result<?> getCode(@PathVariable("type") String type) {
        // 保存验证码信息
        CaptchaEnum captchaEnum = CaptchaEnum.fromValue(type);
        String uuid = IdUtils.simpleUUID();
        Captcha captcha = captchaService.getCode(captchaEnum);

        String value = captcha.getValue();
        String code;
        if (captchaEnum == CaptchaEnum.Math) {
            code = value.substring(value.lastIndexOf("@") + 1);
        } else {
            code = value;
        }
        // 生成验证码
        redisService.set(CAPTCHA_CODE_KEY + uuid, code, 120);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(captcha.getImage(), "jpg", os);
        } catch (IOException e) {
            return Result.error(e.getMessage());
        }

        Result<Map<String, Object>> result = Result.createMap();

        result.getData().put("uuid", uuid);
        result.getData().put("img", Base64.encode(os.toByteArray()));
        return result;
    }
}
